package com.up.upzl.biz.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up.upzl.biz.bean.SysAccountInSession;
import com.up.upzl.biz.common.Constant;
import com.up.upzl.biz.common.UpResult;
import com.up.upzl.biz.domain.SysAccount;
import com.up.upzl.biz.domain.SysAccountLoginLog;
import com.up.upzl.biz.domain.SysAccountLoginLog.LoginStatus;
import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.service.SysAccountLoginLogService;
import com.up.upzl.biz.service.SysAccountService;

/**
 * 系统控制器
 * 
 * @author geeks
 *
 */
@Controller
public class SystemController {

	@Autowired
	private SysAccountService sysAccountService;

	@Autowired
	private SysAccountLoginLogService sysAccountLoginLogService;

	@Autowired
	private Environment env;

	/**
	 * 主页
	 * 
	 * @return 视图名称
	 */
	@GetMapping({ "", "index" })
	public String index() {
		return "index";
	}

	/**
	 * 转发到登陆页面
	 * 
	 * @return 视图名称
	 */
	@GetMapping("login")
	public String login(HttpServletResponse response, HttpServletRequest request) {
		response.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
		SysAccountInSession userInSession = (SysAccountInSession) request.getSession()
				.getAttribute(Constant.USER_IN_SESSION_KEY);
		if (userInSession == null) {
			return "login";
		}
		return "redirect:/index.html";
	}

	/**
	 * 转发到登陆页面
	 * 
	 * @return 登陆状态，提示语
	 */
	@PostMapping("dologin")
	@ResponseBody
	public UpResult doLogin(SysAccount sysAccount, HttpSession session, HttpServletRequest request, String sysIp,
			String userName, Pageable page) {
		// TODO 判断用户是否为空
		if (StringUtils.isEmpty(sysAccount.getAccount())) {
			return UpResult.build(UpResult.PARAM_EXCEPTION, "账号不能为空");
		}
		// TODO 判段密码是否为空
		if (StringUtils.isEmpty(sysAccount.getPassword())) {
			return UpResult.build(UpResult.PARAM_EXCEPTION, "密码不能为空");
		}

		// 根据账号查询用户信息
		SysAccount result = sysAccountService.findAccountByAccount(sysAccount.getAccount());
		if (result == null) { // TODO 判断此用户是否存在
			return UpResult.build(UpResult.NO_RESULT, "账号或密码错误！");
		}
		// 加密密码
		if (!result.getPassword().equals(sysAccount.getPassword())) { // DOTO 判断密码是否正确
			return UpResult.build(UpResult.NO_RESULT, "密码与账户不匹配！");
		}

		sysIp = request.getRemoteAddr();// 客户登陆IP地址

		if (SysAccount.AccountStatus.禁用.equals(result.getAccountStatus())) { // DOTO 判断此账号是否禁用
			return UpResult.build(UpResult.NO_RESULT, "账号已禁用！");
		}

		// 把用户信息存入SESSION
		SysAccountInSession sysAccountInSession = new SysAccountInSession();
		sysAccountInSession.setId(result.getId());// 用户编号
		sysAccountInSession.setName(result.getName());// 用户名
		sysAccountInSession.setAccount(result.getAccount());// 账号
		sysAccountInSession.setSysRole(result.getSysRole());// 角色
		List<SysApp> sysApps = sysAccountService.getSysAppsByUserId(result.getId());
		sysAccountInSession.setSysApps(sysApps);// 所拥有的权限
		session.setAttribute(Constant.USER_IN_SESSION_KEY, sysAccountInSession);

		// 把登陆信息写入日志
		SysAccountLoginLog log = new SysAccountLoginLog();
		log.setIp(request.getRemoteAddr());// 登陆者IP
		log.setSysAccount(result);// 登陆账号
		LoginStatus loginStatus1 = LoginStatus.valueOf("成功");
		log.setLoginStatus(loginStatus1);// 登陆状态
		log.setLoginTime(new Date());// 登陆时间
		sysAccountLoginLogService.save(log);

		return UpResult.build(UpResult.SUCCESS, "登陆成功");
	}

	/**
	 * 登出
	 * 
	 * @param session
	 *            用户会话
	 */
	@GetMapping("logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login";
	}

	/**
	 * 错误页面
	 * 
	 * @return 视图名称
	 */
	@GetMapping("error/{code}.html")
	public String error(@PathVariable String code) {
		return "error/" + code;
	}

	/**
	 * 用于检测服务是否正常启动
	 */
	@GetMapping("heartbeat")
	public @ResponseBody String heartbeat() {
		return env.getActiveProfiles()[0];
	}

	/**
	 * 用于检测服务是否正常启动
	 */
	@GetMapping("challenge")
	public @ResponseBody String challenge() {
		return "envs.push('admin-" + env.getActiveProfiles()[0] + "');";
	}
}
